﻿using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Transponder_Storage;
using Transponder_WebApp.Models;

namespace Transponder_WebApp.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class DeviceInformationController : ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [HttpPost("Add")]
        public Transponder_Core.ResultRespose<int> Add([FromBody] Models.AddDeviceInformationRequest request)
        {

            if (string.IsNullOrEmpty(request.DeviceSn))
            {
                return Transponder_Core.ResultRespose<int>.BadWithData(0, "DeviceSn is null");
            }
            if (string.IsNullOrEmpty(request.DeviceId))
            {
                return Transponder_Core.ResultRespose<int>.BadWithData(0, "DeviceId is null");
            }

            var db = new Db();
            var list = db.DeviceInformation
                 .Where(item => item.DeviceSn == request.DeviceSn
                 || item.DeviceId == request.DeviceId)
                 .ToList();

            if (list.Count > 0)
            {
                return Transponder_Core.ResultRespose<int>.BadWithData(0, "设备已存在。");
            }
            var entity = new DeviceInformation();

            entity.DeviceSn = request.DeviceSn;
            entity.DeviceId = request.DeviceId;

            db.DeviceInformation.Add(entity);
            db.SaveChanges();

            Cache.Update();

            ///
            return Transponder_Core.ResultRespose<int>.OKWithData(0, "。");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        public Transponder_Core.ResultRespose<int> Delete([FromBody] DeleteDeviceInformationRequest  request)
        {

            var db = new Db();

            var list = db.DeviceInformation
                .Where(item => item.Id == request.Id)
                .ToList();

            foreach (var item in list)
            {
                db.DeviceInformation.Remove(item);
            }
            var result = db.SaveChanges();

            Cache.Update();
            return Transponder_Core.ResultRespose<int>.OKWithData(0, "。");


        }

        /// <summary>
        /// 不分页（数据少）
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("List")]
        public Transponder_Core.ResultRespose<IEnumerable<DeviceInformation>> List(string? deviceSn = "", string? deviceId = "")
        {
            var db = new Db();
            return Transponder_Core.ResultRespose<IEnumerable<DeviceInformation>>.OKWithData(db.DeviceInformation
                 .Where(item => !string.IsNullOrEmpty(deviceSn) ? item.DeviceSn.Contains(deviceSn) : true)
                 .Where(item => !string.IsNullOrEmpty(deviceId) ? item.DeviceId.Contains(deviceId) : true)
                 .ToList());

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task< List<DeviceInformation>> GetDeviceInformationList(IFormFile file)
        {
            List<DeviceInformation> devices = new List<DeviceInformation>();
         
            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);

                stream.Seek(0, SeekOrigin.Begin);

                var workbook = new XSSFWorkbook(stream);

                for (var i = 0; i < workbook.NumberOfSheets; i++)
                {
                    var sheet = workbook.GetSheetAt(i);

                    foreach (IRow row in sheet)
                    {
                        var deviceSn = row.GetCell(0)?.ToString();
                        var deviceId = row.GetCell(1)?.ToString();
                        if (!string.IsNullOrEmpty(deviceSn)
                            && !string.IsNullOrEmpty(deviceId))
                        {
                            devices.Add(new DeviceInformation()
                            {
                                DeviceSn = deviceSn,
                                DeviceId = deviceId
                            });
                        }
                    }
                }

            }
            return devices;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="deviceSn"></param>
        /// <param name="deviceId"></param>
        /// <returns></returns>
        [HttpPost("Upload")]
        public async Task<IActionResult> Upload(IFormFile file)
        {


            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded.");
            var devices = await GetDeviceInformationList(file);
             
            Db db = new Db();

            foreach (var device in devices)
            {
                var old= db.DeviceInformation
                    .Where(item => item.DeviceSn == device.DeviceSn)
                    .ToList();
                db.DeviceInformation.RemoveRange(old);
            }

            ///

            db.SaveChanges();

            db.DeviceInformation.AddRange(devices);
            db.SaveChanges();


            return Ok();
        }

    }
}
